from PIL import Image
import json

def merge_source_alpha(sourcePath, alphaPath):
    # 先结合成一张图
    sourceIm = Image.open(sourcePath)
    alphaIm = Image.open(alphaPath)
    r, g, b = sourceIm.split()
    r_a, g_a, b_a = alphaIm.split()
    im = Image.merge("RGBA", (r, g, b, r_a))
    return im


# {"frames": {

#     "1.png":
#     {
#         "frame": {"x":86,"y":1,"w":162,"h":75},
#         "rotated": false,
#         "trimmed": false,
#         "spriteSourceSize": {"x":0,"y":0,"w":162,"h":75},
#         "sourceSize": {"w":162,"h":75}
#     },
# }

def split(sourcePath, alphaPath, jsonPath):
    im = merge_source_alpha(sourcePath, alphaPath)
    print im.format, im.size, im.mode
    with open(jsonPath,"r") as jsonFile:
        frames = json.load(jsonFile)["frames"]
        # 根据json切割
        for var in frames:
            # print var
            curframes = frames[var]["frame"]
            x,y,w,h = curframes["x"],curframes["y"],curframes["w"],curframes["w"]
            print var, x, y, w, h
            
            box = (x, y, x+w, y+h)
            region = im.crop(box)
            region.save(var)



split("test1.tga", "test1_alpha.tga", "test.txt")